import 'dart:async';
import 'dart:math';
import 'dart:typed_data';
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:provider/provider.dart';
import 'package:qclock/main_manager.dart';
import 'package:qclock/setting.dart';
import 'package:qclock/toast.dart';
import 'package:vector_math/vector_math_64.dart' show radians;

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  Provider.debugCheckInvalidValueType = null;
  runApp(
    MultiProvider(
      child: MyApp(),
      providers: [
        ChangeNotifierProvider.value(value: MainManager()..init()),
      ],
    ),
  );
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '轻时钟',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  final GlobalKey globalKey = GlobalKey();

  var radiansPerMilliSeconds = radians(360 / 60000);
  var radialRotation;
  var radialRotationSin;
  var timer;
  bool showMenuBtn = true;

  @override
  void initState() {
    SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeRight]);
    timerInterval();
    timer =
        Timer.periodic(Duration(milliseconds: 30), (t) => {timerInterval()});
    super.initState();
  }

  void timerInterval() {
    setState(() {
      var now = DateTime.now();
      radialRotation =
          (now.second * 1000.0 + now.millisecond) * radiansPerMilliSeconds -
              radians(90);
      radialRotationSin = sin(radialRotation);
    });
  }

  String formateNumber(number) {
    return number < 10 ? '0' + number.toString() : number.toString();
  }

  String formateTime(time, h) {
    if (h) {
      return formateNumber(time.hour) + ':' + formateNumber(time.minute);
    } else {
      var hour =
          time.hour == 24 ? 0 : (time.hour > 12 ? time.hour - 12 : time.hour);
      return formateNumber(hour) + ':' + formateNumber(time.minute);
    }
  }

  Future<Uint8List> _capturePng() async {
    setState(() {
      showMenuBtn = false;
    });

    try {
      Future.delayed(Duration(milliseconds: 100), () async {
        RenderRepaintBoundary boundary =
            globalKey.currentContext.findRenderObject();
        var image = await boundary.toImage(pixelRatio: 3.0);
        ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
        Uint8List pngBytes = byteData.buffer.asUint8List();
        final result = await ImageGallerySaver.saveImage(pngBytes,
            quality: 100, name: "轻时钟");
        Toast.show(context,
            msg: '保存${result['isSuccess'] ? "成功" : "失败"}', duration: 1);
        setState(() {
          showMenuBtn = true;
        });
      });
    } catch (e) {
      print(e);
      setState(() {
        showMenuBtn = true;
      });
    }
    return null;
  }

  @override
  void dispose() {
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
    timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    MainManager _mainManager = Provider.of<MainManager>(context);
    return Scaffold(
      key: _scaffoldKey,
      endDrawer: Drawer(
        child: Setting(),
      ),
      body: RepaintBoundary(
        key: globalKey,
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height,
                decoration: BoxDecoration(
                  gradient: SweepGradient(
                    colors: [
                      _mainManager.primaryColorDark,
                      _mainManager.primaryColor,
                      _mainManager.primaryColorLight,
                    ],
                    stops: [0.0 + radialRotationSin * 0.0001, 0.5, 1],
                    transform: GradientRotation(radialRotation),
                  ),
                ),
                child: ShaderMask(
                  shaderCallback: (Rect bounds) {
                    return SweepGradient(
                      colors: [
                        Color(0xFFFFFFFF),
                        _mainManager.primaryColorLight,
                        Color(0xFF000000),
                      ],
                      stops: [0.0 + radialRotationSin * 0.0001, 0.5, 1],
                      transform: GradientRotation(radialRotation),
                      tileMode: TileMode.mirror,
                    ).createShader(bounds);
                  },
                  blendMode: BlendMode.srcATop,
                  child: Container(
                    padding: EdgeInsets.fromLTRB(60, 30, 60, 50),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            // Container(height: 50),
                            showMenuBtn
                                ? IconButton(
                                    icon: Icon(
                                      Icons.download_rounded,
                                      size: 24,
                                    ),
                                    onPressed: () {
                                      _capturePng();
                                    },
                                  )
                                : Container(),
                            showMenuBtn
                                ? IconButton(
                                    icon: Icon(
                                      Icons.menu,
                                      size: 28,
                                    ),
                                    onPressed: () {
                                      _scaffoldKey.currentState.openEndDrawer();
                                    },
                                  )
                                : Container(),
                          ],
                        ),
                        _mainManager.showTimeStatus
                            ? Text(
                                formateTime(DateTime.now(), _mainManager.h24),
                                style: TextStyle(
                                  color: Colors.white,
                                  fontStyle: FontStyle.italic,
                                  fontSize: 100,
                                  fontWeight: FontWeight.w100,
                                ),
                              )
                            : Container(),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            _mainManager.showSecondStatus
                                ? Text(
                                    formateNumber(DateTime.now().second),
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontStyle: FontStyle.italic,
                                      fontSize: 50,
                                      fontWeight: FontWeight.w200,
                                    ),
                                  )
                                : Container(),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
